import type { FormInstance } from 'element-plus'
import type {
  operationStatusEnum,
  facilityTypeEnum
} from '~/store/assetManagement/facilityManagement/typings'
import type {
  PowerDistributionFacilitiesDataItemType,
  PowerDistributionFacilitiesOptionsPropsType
} from '../../facilityManagement/powerDistributionFacilities/typings'
import type { workAreaEnum } from '~/store/assetManagement/assetAreaManage/typings'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  // ElSwitch,
  ElRadioGroup,
  ElRadioButton,
  ElLink,
  ElIcon
} from 'element-plus'
import { Plus, WarningFilled } from '@element-plus/icons-vue'
import InputTextarea from '~/components/ProForm/InputTextarea'
import BaseUpload from '~/components/ProForm/BaseUpload'
import useVuexGetters from '~/hooks/useVuexGetters'
// import { handleTrim } from '~/utils/util'
import styles from '../../index.module.scss'

export default defineComponent({
  name: 'BasicInformation',
  props: ['detail', 'type'],
  setup: (
    props: {
      detail: PowerDistributionFacilitiesDataItemType
      type: PowerDistributionFacilitiesOptionsPropsType['type']
    },
    { expose }
  ) => {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const optionsValidateForm = reactive<PowerDistributionFacilitiesDataItemType>(
      Object.assign(
        {
          isDeliver: true,
          imageUrl: []
        },
        props?.detail?.id // 初始化数据
          ? {
              id: props.detail.id,
              name: props.detail.name,
              categoryId: props.detail.categoryId,
              tenKv: props.detail.tenKv,
              highNo: props.detail.highNo,
              capacity: props.detail.capacity,
              deliverDate: props.detail.deliverDate,
              memo: props.detail.memo,
              isDeliver: props.detail?.isDeliver,
              workAreaId: props.detail?.workAreaId,
              streetId: props.detail?.streetId,
              // isDeliver: !!(props.detail?.isDeliver ?? 1),
              imageUrl: props.detail?.imageUrl
                ? (props.detail?.imageUrl as string)?.split?.(',')
                : []
            }
          : { isDeliver: 1 }
      )
    )
    const powerDistributionFacilitiesState = useVuexGetters('powerDistributionFacilities', [
      'tenantDictDictionaryOpt',
      'facilityTypeEnum',
      'operationStatusSelectList'
    ])
    const assetWorkAreaState = useVuexGetters('assetWorkArea', ['workAreaSelectList'])
    const streetManagementState = useVuexGetters('streetManagement', ['streetSelectList'])

    // 投运状态change事件
    const handleChangeDeliver = (value: string | number | boolean) => {
      if (!value) optionsValidateForm.deliverDate = undefined
    }

    // 上传成功回调
    const handleUploadSuccess = (result: Record<string, any>) => {
      const link = result?.data?.link
      if (link) {
        (optionsValidateForm.imageUrl as string[])?.push(link)
      }
    }
    // 移除对应的文件
    const handleRemoveUploadFile = (file: Record<string, any>) => {
      const link = file?.response?.data?.link || file?.url
      if (link) {
        optionsValidateForm.imageUrl = (optionsValidateForm.imageUrl as string[])?.filter(
          (item) => item !== link
        )
      }
    }
    // 切换工区回调
    const handleChangeWorkArea = (workAreaId: string) => {
      optionsValidateForm.streetId = undefined
      handleGetStreetSelectList(workAreaId)
    }

    // 获取所属街道下拉列表
    const handleGetStreetSelectList = (workAreaId: string) => {
      store.dispatch('streetManagement/GetStreetSelectListByUser', { workAreaId })
    }
    onMounted(() => {
      if (props.detail?.workAreaId) handleGetStreetSelectList(props.detail?.workAreaId)
    })
    expose({ ruleFormRef, formValues: optionsValidateForm })

    return () => {
      return (
        <ElForm
          ref={ruleFormRef}
          model={optionsValidateForm}
          labelWidth="120px"
          labelPosition="right"
        >
          <ElFormItem
            prop="name"
            label="设施名称"
            rules={[
              { required: true, whitespace: true, message: '请输入设施名称' },
              { min: 3, whitespace: true, message: '设施名称长度为3～20字符' }
            ]}
          >
            <ElInput v-model={optionsValidateForm.name} {...{ minlength: 3, maxlength: 20 }} />
          </ElFormItem>
          <ElFormItem
            prop="categoryId"
            label="设施类型"
            rules={[{ required: true, message: '请选择设施类型' }]}
          >
            <ElSelect v-model={optionsValidateForm.categoryId}>
              {powerDistributionFacilitiesState.tenantDictDictionaryOpt?.value?.map(
                (item: facilityTypeEnum) => (
                  <ElOption key={item?.id} label={item?.dictValue} value={item?.id!} />
                )
              ) || []}
            </ElSelect>
          </ElFormItem>
          <ElFormItem
            prop="isDeliver"
            label="投运状态"
            rules={[{ required: true, message: '请选择投运状态' }]}
          >
            {/* <ElSwitch
              v-model={optionsValidateForm.isDeliver}
              disabled={props.type === 'update' && !!props.detail?.isDeliver}
              onChange={handleChangeDeliver}
            /> */}
            <ElRadioGroup
              class={styles['info-form-item-full-width']}
              v-model={optionsValidateForm.isDeliver}
              disabled={props.type === 'update' && !!props.detail?.isDeliver}
              onChange={handleChangeDeliver}
            >
              {powerDistributionFacilitiesState.operationStatusSelectList.value?.map(
                (item: operationStatusEnum) => (
                  <ElRadioButton label={item.dictKey}>{item.dictValue}</ElRadioButton>
                )
              )}
            </ElRadioGroup>
          </ElFormItem>
          <ElFormItem
            prop="deliverDate"
            label="投运日期"
            rules={[{ required: false, message: '请输入投运日期' }]}
          >
            <ElDatePicker
              class={styles['info-form-item-full-width']}
              v-model={optionsValidateForm.deliverDate}
              disabled={!optionsValidateForm.isDeliver}
            />
          </ElFormItem>
          <ElFormItem
            prop="workAreaId"
            label="所属区域"
            rules={[{ required: true, message: '请选择所属区域' }]}
          >
            <ElSelect v-model={optionsValidateForm.workAreaId} onChange={handleChangeWorkArea}>
              {assetWorkAreaState.workAreaSelectList?.value?.map((item: workAreaEnum) => (
                <ElOption key={item?.id} label={item?.name} value={item?.id!} />
              )) || []}
            </ElSelect>
          </ElFormItem>
          <ElFormItem
            prop="streetId"
            label="所属街道"
            rules={[{ required: false, message: '请选择所属街道' }]}
          >
            <ElSelect v-model={optionsValidateForm.streetId}>
              {streetManagementState.streetSelectList?.value?.map((item: workAreaEnum) => (
                <ElOption key={item?.id} label={item?.name} value={item?.id!} />
              )) || []}
            </ElSelect>
          </ElFormItem>
          <ElFormItem
            prop="tenKv"
            label="所属10kV线路"
            rules={[{ required: false, message: '请输入所属10kV线路' }]}
          >
            <ElInput v-model={optionsValidateForm.tenKv} {...{ maxlength: 50 }} />
          </ElFormItem>
          <ElFormItem
            prop="highNo"
            label="高压杆号"
            rules={[{ required: false, message: '请输入高压杆号' }]}
          >
            <ElInput v-model={optionsValidateForm.highNo} {...{ maxlength: 20 }} />
          </ElFormItem>
          <ElFormItem
            prop="capacity"
            label="空开容量"
            rules={[{ required: false, message: '请输入空开容量' }]}
          >
            <ElInput v-model={optionsValidateForm.capacity} {...{ maxlength: 20 }} />
          </ElFormItem>
          <ElFormItem prop="memo" label="备注" rules={[{ required: false, message: '请输入备注' }]}>
            <InputTextarea
              v-model:inputTextareaValue={optionsValidateForm.memo}
              placeholderName="输入内容"
              limitLength={100}
            />
          </ElFormItem>
          <ElFormItem
            label="图片"
            prop="imageUrl"
            rules={[{ required: false, message: '请上传图片', trigger: 'change' }]}
          >
            <BaseUpload
              listType="picture-card"
              fileList={(optionsValidateForm.imageUrl as string[])?.map?.((item) => ({
                name: '图片',
                url: item
              }))}
              accept=".jpg,.png"
              limit={12}
              onSuccess={handleUploadSuccess}
              onRemove={handleRemoveUploadFile}
              v-slots={{
                tip: () => (
                  <section>
                    <ElLink type="info" underline={false} icon={<WarningFilled />}>
                      支持最多上传12张图片
                      {/* 支持最多上传12张图片, 且单张图片大小在16M以内 */}
                    </ElLink>
                  </section>
                )
              }}
            >
              <ElIcon>
                <Plus />
              </ElIcon>
            </BaseUpload>
          </ElFormItem>
        </ElForm>
      )
    }
  }
})
